<template>
	<view>
		<u-navbar :title="navDesc" :autoBack="true" :bgColor="them_color" :titleStyle="{color:'#ffffff'}"
			leftIconColor="#ffffff"></u-navbar>
		<form @submit="formSubmit">
			<view class='addAddress' :style="'margin-top:' + navH + 'px;'">
				<view class='list'>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>姓名</view>
						<input type='text' placeholder='请输入姓名' name='consignee' :value="userAddress.consignee" 
							placeholder-class='placeholder'></input>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>联系电话</view>
						<input type='number' placeholder='请输入联系电话' name="mobile" :value='userAddress.mobile'
							placeholder-class='placeholder' pattern="\d*"></input>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>所在地区</view>
						<view class="address" @click="pickerShow=true">
							<view class='acea-row'>
								<view class="picker">{{areaContent || '省、市、区'}}</view>
							</view>
						</view>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>详细地址</view>
						<input type='text' placeholder='请填写具体地址' name='address' placeholder-class='placeholder'
							:value='userAddress.address'></input>
					</view>
				</view>
				<view class='default acea-row row-middle'>
					<u-checkbox-group @change='ChangeIsDefault'>
						<u-checkbox :checked="userAddress.is_default ? true : false" />设置为默认地址
					</u-checkbox-group>
				</view>
				<button class='keepBnt bg-color' form-type="submit">立即保存</button>
			</view>
		</form>

		<!-- 地区选择器 -->
		<view>
			<u-picker :show="pickerShow" ref="uPicker" :columns="areaList" keyName="region_name"
				:closeOnClickOverlay="true" :defaultIndex="currentIndex" @change="areaChange" @confirm="areaConfirm"
				@close="areaClose" @cancel="areaCancel">
			</u-picker>
		</view>
	</view>
</template>

<script>
	let sysHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import {
		address_edit_add,
		address_info,
		get_regions
	} from '@/api/user.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";

	export default {
		data() {
			return {
				navDesc:'',
				navH: '',
				them_color: getApp().globalData.theme_color,
				address_id: 0, //地址id
				userAddress: {
					consignee: '', //收货人
					mobile: '', //手机号
					address: '', //详细地址
					zipcode: '', //邮政编码
					country: '0', //国家id - 默认是0中国
					province: '', //省id
					city: '', //市id
					district: '', //县、城区id
					tel: '', //国定电话
					is_default: '', //默认地址 - 1 ：默认地址 0：不是默认地址
					address_id: '', //地址id 编辑时传
				},

				pickerShow: false,
				areaContent: '',
				//选择区域的联动数据
				areaList: [],
				currentIndex: [0, 0, 0],
				//选择器的列发生改变时的索引值
				changeIndex: [0, 0, 0],
			};
		},
		computed: mapGetters(['isLogin', 'app_token']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.getUserAddress();
					}
				},
				deep: true
			}
		},
		async onLoad(options) {
			this.navH = getApp().globalData.navHeight / 2;
			if (this.isLogin) {
				this.address_id = options.address_id || 0;
				uni.setNavigationBarTitle({
					title: options.address_id ? '修改地址' : '添加地址'
				})
				this.navDesc = options.address_id ? '修改地址' : '添加地址';
				await this.getUserAddress();
               
			} else {
				toLogin();
			}

			let province = '' //省
			let city = '' //市
			let area = '' //区

            if(options.address_id){	
				// 初始化地区选中的数据和索引值
				province = await this.getAreaData()
				const proIndex = province.findIndex(val => val.region_id == this.userAddress.province)
				
				city = await this.getAreaData(province[proIndex].region_id)
				const cityIndex = city.findIndex(val => val.region_id == this.userAddress.city)
				
				area = await this.getAreaData(city[cityIndex].region_id)
				const areaIndex = area.findIndex(val => val.region_id == this.userAddress.district)
				
				this.currentIndex = [proIndex, cityIndex, areaIndex]
				this.changeIndex = [proIndex, cityIndex, areaIndex]
				
				//设置三列对应的数据
				this.$set(this.areaList, '0', province)
				this.$set(this.areaList, '1', city)
				this.$set(this.areaList, '2', area)
				
				this.areaContent =
					`${this.userAddress.province_name} , ${this.userAddress.city_name} , ${this.userAddress.district_name}`;
			
			}else{
				province = await this.getAreaData()
				city = await this.getAreaData(province[0].region_id)
				area = await this.getAreaData(city[0].region_id)
				
				this.$set(this.areaList,'0',province)
				this.$set(this.areaList,'1',city)
				this.$set(this.areaList,'2',area)
			}
		

		},
		methods: {
			async getAreaData(region_id = 1) {
				var that = this;
				const {
					data
				} = await get_regions({
					region_id: region_id,
					app_token: that.app_token
				})
				return data;
			},
			//区域选择器进行选择时处理
			async areaChange(e) {
				const {
					columnIndex,
					index,
					indexs,
					picker = this.$refs.uPicker
				} = e
				let city = '' //市
				let area = '' //区

				if (columnIndex === 0) {
					// 修改第2列的值
					city = await this.getAreaData(this.areaList[columnIndex][index].region_id)
					picker.setColumnValues(1, city)
					this.areaList[1] = city

					//修改第3列的值
					area = await this.getAreaData(city[0].region_id)
					picker.setColumnValues(2, area)
					this.areaList[2] = area

				} else if (columnIndex === 1) {
					//修改第3列
					area = await this.getAreaData(this.areaList[columnIndex][index].region_id)
					picker.setColumnValues(2, area)
					this.areaList[2] = area

				} else {
				
				}
				//记录改变的索引值
				this.changeIndex[columnIndex] = index

			},
			//点击区域选择器确定按钮处理
			areaConfirm(e) {
				const {
					indexs,
					value
				} = e
				this.pickerShow = false
				this.currentIndex = indexs
				let area = value[2]
				// 海南没有区,无属性时候会报错,添加个region_name默认值可解决
				if (!area) {
					area = {
						region_name: ''
					}
				}

				this.areaContent = `${value[0].region_name}-${value[1].region_name}-${area.region_name || '未知'}`
			},
			//点击区域选择器 取消 按钮处理
			areaCancel() {
				this.pickerClose()
			},
			//点击区域选择器 遮罩 处理
			areaClose() {
				this.pickerClose()
			},
			//区域选择器被关闭处理 - 根据上次确定后的索引值重置数据 & 隐藏选择器
			async pickerClose() {
				this.pickerShow = false
				//防止没进行列的改变再重复 重置数据
				if (this.currentIndex.toString() == this.changeIndex.toString()) {
					return false
				}
				//根据当前选择的地域索引值重置数据
				const picker = this.$refs.uPicker
				// 第2列处理
				const city = await this.getAreaData(this.areaList[0][this.currentIndex[0]].region_id)
				picker.setColumnValues(1, city)
				this.areaList[1] = city
				//第3列处理
				const area = await this.getAreaData(this.areaList[1][this.currentIndex[1]].region_id)
				picker.setColumnValues(2, area)
				this.areaList[2] = area
				//设置对应列的选择值
				picker.setIndexs(this.currentIndex)
				this.changeIndex = JSON.parse(JSON.stringify(this.currentIndex))
			},

			async getUserAddress() {
				if (!this.address_id) return false;
				let that = this;
				const {
					data
				} = await address_info({
					app_token: that.app_token,
					address_id: that.address_id
				})

				this.userAddress = data
			},

			/**
			 * 提交用户添加地址
			 * 
			 */
			formSubmit: function(e) {
				let that = this,
					value = e.detail.value;
				if (!value.consignee.trim()) return that.$util.Tips({
					title: '请填写收货人姓名'
				});
				if (!value.mobile) return that.$util.Tips({
					title: '请填写联系电话'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.mobile)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				// if ( ) return that.$util.Tips({
				// 	title: '请选择所在地区'
				// });
				if (!value.address.trim()) return that.$util.Tips({
					title: '请填写详细地址'
				});


				if (!that.areaContent) {
					uni.$u.toast('请选择区域')
					return false
				}

				// 取地区id
				that.userAddress.province = that.areaList[0][that.currentIndex[0]].region_id
				that.userAddress.city = that.areaList[1][that.currentIndex[1]].region_id
				that.userAddress.district = that.areaList[2][that.currentIndex[2]].region_id
				that.userAddress.is_default = that.userAddress.is_default ? 1 : 0;
				that.userAddress.address_id = that.address_id;
				that.userAddress.consignee = value.consignee;
				that.userAddress.address = value.address;
				that.userAddress.mobile = value.mobile;
				
				uni.showLoading({
					title: '正在提交',
					mask: true,
					success: async () => {
						//将数据传到服务器
						const res = await address_edit_add({
							app_token: that.app_token,
							...that.userAddress
						})
						if (res.status === 0) {
							if (that.address_id)
								that.$util.Tips({
									title: '修改成功',
									icon: 'success'
								});
							else
								that.$util.Tips({
									title: '添加成功',
									icon: 'success'
								});
							setTimeout(function() {
								 uni.navigateBack({
									delta: 1,
								})
							}, 1000);
						}

					},
					complete: () => {
						uni.hideLoading()
					}
				});

			},
			ChangeIsDefault: function(e) {
				this.$set(this.userAddress, 'is_default', !this.userAddress.is_default);
			}
		}
	}
</script>

<style scoped lang="scss">
	.fontcolor {
		color: var(--view-theme);
	}

	.addAddress .list {
		background-color: #fff;
	}

	.addAddress .list .item {
		padding: 30rpx;
		border-top: 1rpx solid #eee;
	}

	.addAddress .list .item .name {
		width: 195rpx;
		font-size: 30rpx;
		color: #333;
	}

	.addAddress .list .item .address {
		// width: 412rpx;
		flex: 1;
		margin-left: 20rpx;
	}

	.addAddress .list .item input {
		width: 475rpx;
		font-size: 30rpx;
	}

	.addAddress .list .item .placeholder {
		color: #ccc;
	}

	.addAddress .list .item picker {
		width: 475rpx;
	}

	.addAddress .list .item picker .picker {
		width: 410rpx;
		font-size: 30rpx;
	}

	.addAddress .list .item picker .iconfont {
		font-size: 43rpx;
	}

	.addAddress .default {
		padding: 0 30rpx;
		height: 90rpx;
		background-color: #fff;
		margin-top: 23rpx;
	}

	.addAddress .default checkbox {
		margin-right: 15rpx;
	}

	.addAddress .keepBnt {
		width: 690rpx;
		height: 86rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 86rpx;
		margin: 50rpx auto;
		font-size: 32rpx;
		color: #fff;
	}

	.addAddress .wechatAddress {
		width: 690rpx;
		height: 86rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 86rpx;
		margin: 0 auto;
		font-size: 32rpx;
		color: var(--view-theme);
		border: 1px solid var(--view-theme);
	}
</style>
